package org.meb.lotrlcg.web;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

import org.apache.commons.lang.StringUtils;
import org.meb.lotrlcg.db.model.CardSet;
import org.meb.lotrlcg.db.model.Domain;
import org.meb.lotrlcg.db.model.EncounterSet;
import org.meb.lotrlcg.db.model.Scenario;

@Getter
@Setter
@RequiredArgsConstructor
@AllArgsConstructor
public class AutoCompleteItem {

	@NonNull
	private String id;

	@NonNull
	private String name;
	private Object target;

	public static String createUniqueId(Object o) {
		Object[] parts;
		if (o instanceof CardSet) {
			parts = new Object[] { "cardSet", ((CardSet) o).getId() };
		} else if (o instanceof EncounterSet) {
			parts = new Object[] { "encounterSet", ((EncounterSet) o).getId() };
		} else if (o instanceof Scenario) {
			parts = new Object[] { "scenario", ((Scenario) o).getId() };
		} else if (o instanceof Domain) {
			parts = new Object[] { "domain", ((Domain) o).getId(), ((Domain) o).getValue() };
		} else {
			throw new IllegalArgumentException("Unsupported type: " + o);
		}
		return StringUtils.join(parts, '#');
	}

	public static Object createTarget(String id) {
		String[] tokens = id.split("#");

		Object target;
		if ("cardSet".equals(tokens[0])) {
			target = new CardSet(Long.valueOf(tokens[1]));
		} else if ("encounterSet".equals(tokens[0])) {
			target = new EncounterSet(Long.valueOf(tokens[1]));
		} else if ("scenario".equals(tokens[0])) {
			target = new EncounterSet(Long.valueOf(tokens[1]));
		} else {
			throw new IllegalArgumentException("Unsupported type: " + id);
		}
		return target;
	}

	public static AutoCompleteItem create(Object target) {
		AutoCompleteItem item;
		if (target instanceof CardSet) {
			item = create((CardSet) target);
		} else if (target instanceof EncounterSet) {
			item = create((EncounterSet) target);
		} else if (target instanceof Scenario) {
			item = create((Scenario) target);
		} else if (target instanceof Domain) {
			item = create((Domain) target);
		} else {
			throw new IllegalArgumentException("Unsupported type: " + target);
		}
		return item;
	}

	public static AutoCompleteItem create(CardSet target) {
		String uniqueId = createUniqueId(target);
		return new AutoCompleteItem(uniqueId, target.getName(), target);
	}

	public static AutoCompleteItem create(EncounterSet target) {
		String uniqueId = createUniqueId(target);
		return new AutoCompleteItem(uniqueId, target.getName(), target);
	}
	
	public static AutoCompleteItem create(Scenario target) {
		String uniqueId = createUniqueId(target);
		return new AutoCompleteItem(uniqueId, target.getName(), target);
	}

	public static AutoCompleteItem create(Domain target) {
		String uniqueId = createUniqueId(target);
		return new AutoCompleteItem(uniqueId, target.getDescription(), target);
	}
}
